<?php
namespace Shakemobile\Model;
use Think\Model;
class LotteryModel {
	public $eid;
	public $event_uid;
	public $shop_uid;
	public $sys_uid;
	public $shopcfg;
	public $score; //当前用户的抽奖次数
	
	public function check_event(){
		if(!$this->shopcfg){
			$reda["success"] = 3;
			$reda["title"] = "抱歉，没有这个活动！";			
			$reda["status"]=false;
			$reda["score"]=0;
			$reda["code"] = "no game";
			$reda["giftname"]="抱歉，没有这个活动！";	
		}elseif(strtotime($this->shopcfg["start_time"])>time()){
			$reda["success"] = 3;
			$reda["title"] = "活动尚未开始！";
			$reda["status"]=false;
			$reda["code"] = "watting";
			$reda["score"]=0;
			$reda["giftname"]="活动尚未开始！";	
		}elseif(strtotime($this->shopcfg["end_time"])<time()){
			$reda["success"] = 3;
			$reda["title"] = "活动已经结束！";
			$reda["code"] = "time out";
			$reda["status"]=false;
			$reda["score"]=0;
			$reda["giftname"]="活动已经结束！";	
		}else{
			$reda["status"]=true;
		}
		return $reda;
	}
	
	public function do_lott(){
		if($this->score>0){
			$re = $this->ShopLotter();
			if($re>0){
				$reda["status"]=true;
				$reda["success"]=1;
			}else{
				$reda["status"]=false;
				$reda["success"]=2;
			}
			$reda["giftname"]=$this->gifts[$re]["name"];	
			$reda["giftpic"]=$this->gifts[$re]["pic_url"];	
			$reda["type"]=$this->gifts[$re]["type"];	
			$reda["level"]=$this->gifts[$re]["level"];	
			$reda["getway"]=$this->gifts[$re]["ext_rule"];	
			if($this->gifts[$re]["type"]==4){
				$reda["cardno"]=$this->gifts[$re]["cardno"];
				$reda["secret"]=$this->gifts[$re]["secret"];
			}else{
				$reda["withdraw"]=$this->gifts[$re]["num_iids"];	
			}
			$reda["gid"]=$re;	
			// $reda["ugid"]=$this->ugid;	
			$reda["mygid"]=$this->ugid;	
			$reda["score"].='您还有'.--$this->score.'次机会！';				
		}else{
			$reda["status"]=false;
			$reda["success"]=4;
			$reda["giftname"]="您的抽奖机会已经用完啦！";	
		}
		$reda["score"]=$this->score;
		return $reda;
	}
	
	private function ShopLotter(){
		foreach($this->gifts as $k=>$gift){ //中奖率分布
			if($gift["quantity"]>0){
				$LotArr[$k]=$gift["probability"];
			}else{
				$nonequantity += $gift["probability"];
				//数量为0的奖品概率要增加到不中奖
			}
		}
		if($this->eid==0){$i=10000;}else{ $i = 10000000;}
		if(array_sum($LotArr)<i){
			$none = array(
				"name"=>"再接再厉，大奖不远啦！",
				"probability"=>i-array_sum($LotArr)+$nonequantity,
				"quantity"=>0,
				"type"=>0,
			);
			$this->gifts[0]=$none;
			$LotArr[0]=i-array_sum($LotArr)+$nonequantity;
		}
		// 中奖率分布结束，抽取
		$re = $this->Lottery($LotArr);
		$UG = D("UsersGifts");
		if($re<>0){
			if($this->gifts[$re]["type"]==4){
				// 中得卡密要保存卡密id
				$KM = M("EventsGiftsKm");
				$kami = current($KM->where("`giftid`=".$re." AND `sid`=".$this->sid." AND `status`=8")->getField("`id`,`id`,`cardno`,`secret`"));
				if($kami){
					$data["kamiid"]=$kami["id"];
					$this->gifts[$re]["cardno"]=$kami["cardno"];
					$this->gifts[$re]["secret"]=$kami["secret"];
					$kmsv["status"]=9;
					$kmsv["shopuid"]=$this->shop_uid;
					$KM->where("`id`=".$kami["id"])->save($kmsv);
				}else{
					$this->gifts[$re]["cardno"]="没有卡号";
					$this->gifts[$re]["secret"]="";
				}
			}
			$data["eventid"]=$this->eid;
			$data["giftid"]=$re;
			$data["sys_giftid"]=$this->gifts[$re]["gift_id"];
			$data["uzuid"]=$this->shop_uid;
			$data["event_user_id"] = $this->event_uid;
			$data["user_nick"] = "";
			$data["sid"]=$this->sid;
			$data["gtype"]=$this->gifts[$re]["type"];
			$data["gift_name"]=$this->gifts[$re]["name"];
			$data["gift_pic_url"]=$this->gifts[$re]["pic_url"];
			$data["getway"]=$this->gifts[$re]["ext_rule"];
			// $data["kamiid"]=$kami["id"];
			$data["actiontime"]=date("Y-m-d H:i:s",time());
			$tp=Array(2,3,4,5,6,7);//除实物外的奖品设置为已发奖状态
			if(in_array($this->gifts[$re]["type"],$tp)){
				$data["status"]=1;
			}
			$this->ugid = $UG->add($data); //为用户增加一个中奖记录
			if($this->gifts[$re]["adv_win"]){
				$adv = ",advance_wins = advance_wins+1";
			}
			$UG->execute("update `__PREFIX__events_gifts` set `quantity` = IF(`quantity`<1, 0, `quantity`-1) ".$adv." WHERE `id` = ".$re);

			if($this->gifts[$re]["type"]!=7){
				$wins = ", `wins` = `wins`+1 ";//echo $event_uid.$U->_sql();
			}
		}
		$USR = M("Friends");
		$USR->where(Array("id"=>$this->event_uid))->setDec("score");
		// $UG->execute("update `shake_friends` set `score` = IF(`score`<1, 0, `score`-1) WHERE `id` = ".$this->event_uid);//echo $event_uid.$U->_sql();
		$UG->execute("update `shake_shop_cfg` set `lotts` = `lotts`+1".$wins." WHERE `sid` = ".$this->sid);//echo $event_uid.$U->_sql();
		return $re;
	}
	private function Lottery($proArr){

	/*
	 * 经典的概率算法，
	 * $proArr是一个预先设置的数组，
	 * 假设数组为：array(100,200,300，400)，
	 * 开始是从1,1000 这个概率范围内筛选第一个数是否在他的出现概率范围之内， 
	 * 如果不在，则将概率空间，也就是k的值减去刚刚的那个数字的概率空间，
	 * 在本例当中就是减去100，也就是说第二个数是在1，900这个范围内筛选的。
	 * 这样 筛选到最终，总会有一个数满足要求。
	 * 就相当于去一个箱子里摸东西，
	 * 第一个不是，第二个不是，第三个还不是，那最后一个一定是。
	 * 这个算法简单，而且效率非常 高，
	 * 关键是这个算法已在我们以前的项目中有应用，尤其是大数据量的项目中效率非常棒。
	 */

    $result = '';  
    //概率数组的总概率精度 
    $proSum = array_sum($proArr);  
    //概率数组循环 
    foreach ($proArr as $key => $proCur) { 
        $randNum = mt_rand(1, $proSum); 
        if ($randNum <= $proCur) { 
            $result = $key; 
            break; 
        } else { 
            $proSum -= $proCur; 
        } 		
    } 
    unset ($proArr);  
    return $result; 
	}
}